import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { type MenuFormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h, toRaw } from "vue";

export function useMenu() {
  const form = reactive({
    title: "",
    status: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "菜单编号",
      prop: "id",
      minWidth: 90
    },
    {
      label: "菜单名称",
      prop: "title",
      minWidth: 120,
      align: "left"
    },
    {
      label: "图标",
      prop: "icon",
      minWidth: 80,
      cellRenderer: ({ row, props }) => (
        <i class={[row.icon, "text-lg"]} style="margin-right: 8px;" />
      )
    },
    {
      label: "路由地址",
      prop: "path",
      minWidth: 150
    },
    {
      label: "组件路径",
      prop: "component",
      minWidth: 150
    },
    {
      label: "权限标识",
      prop: "permission",
      minWidth: 120
    },
    {
      label: "类型",
      prop: "type",
      minWidth: 80,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={
            row.type === 1 ? "primary" : row.type === 2 ? "success" : "info"
          }
          effect="plain"
        >
          {row.type === 1 ? "目录" : row.type === 2 ? "菜单" : "按钮"}
        </el-tag>
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.status === 1 ? "success" : "danger"}
          effect="plain"
        >
          {row.status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 80
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function onSearch() {
    loading.value = true;
    // 模拟请求延时
    setTimeout(() => {
      dataList.value = getMenuList(toRaw(form));
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: MenuFormItemProps) {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          id: row?.id ?? null,
          parentId: title === "新增" && row ? row.id : row?.parentId ?? 0,
          title: row?.title ?? "",
          path: row?.path ?? "",
          component: row?.component ?? "",
          icon: row?.icon ?? "",
          permission: row?.permission ?? "",
          type: row?.type ?? 1,
          status: row?.status ?? 1,
          sort: row?.sort ?? 0,
          visible: row?.visible ?? true,
          keepAlive: row?.keepAlive ?? false,
          remark: row?.remark ?? ""
        }
      },
      width: "50%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as MenuFormItemProps;
        function chores() {
          message(`您${title}了菜单名称为${curData.title}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 实际开发先调用相应接口，再进行下面操作
            if (title === "新增" || title === "新增子菜单") {
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  function handleDelete(row) {
    ElMessageBox.confirm(
      `确认要删除菜单名称为"${row.title}"的这条数据吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )
      .then(() => {
        console.log("删除菜单", row);
        // 实际开发先调用删除接口，再进行下面操作
        message(`您删除了菜单名称为${row.title}的这条数据`, {
          type: "success"
        });
        onSearch();
      })
      .catch(() => {});
  }

  /** 菜单列表 */
  function getMenuList(params: any) {
    // 模拟数据，实际开发中替换为真实的API调用
    let menuData = [
      {
        id: 1,
        parentId: 0,
        title: "系统管理",
        path: "/system",
        component: "",
        icon: "setting",
        permission: "system",
        type: 1,
        status: 1,
        sort: 1,
        visible: true,
        keepAlive: false,
        remark: "系统管理目录",
        createTime: new Date(),
        children: [
          {
            id: 11,
            parentId: 1,
            title: "用户管理",
            path: "/system/user",
            component: "system/user/index",
            icon: "user",
            permission: "system:user:list",
            type: 2,
            status: 1,
            sort: 1,
            visible: true,
            keepAlive: true,
            remark: "用户管理菜单",
            createTime: new Date(),
            children: [
              {
                id: 111,
                parentId: 11,
                title: "用户查询",
                path: "",
                component: "",
                icon: "",
                permission: "system:user:query",
                type: 3,
                status: 1,
                sort: 1,
                visible: true,
                keepAlive: false,
                remark: "用户查询按钮",
                createTime: new Date()
              },
              {
                id: 112,
                parentId: 11,
                title: "用户新增",
                path: "",
                component: "",
                icon: "",
                permission: "system:user:add",
                type: 3,
                status: 1,
                sort: 2,
                visible: true,
                keepAlive: false,
                remark: "用户新增按钮",
                createTime: new Date()
              }
            ]
          },
          {
            id: 12,
            parentId: 1,
            title: "角色管理",
            path: "/system/role",
            component: "system/role/index",
            icon: "role",
            permission: "system:role:list",
            type: 2,
            status: 1,
            sort: 2,
            visible: true,
            keepAlive: true,
            remark: "角色管理菜单",
            createTime: new Date()
          },
          {
            id: 13,
            parentId: 1,
            title: "菜单管理",
            path: "/system/menu",
            component: "system/menu/index",
            icon: "menu",
            permission: "system:menu:list",
            type: 2,
            status: 1,
            sort: 3,
            visible: true,
            keepAlive: true,
            remark: "菜单管理菜单",
            createTime: new Date()
          }
        ]
      },
      {
        id: 2,
        parentId: 0,
        title: "系统监控",
        path: "/monitor",
        component: "",
        icon: "monitor",
        permission: "monitor",
        type: 1,
        status: 1,
        sort: 2,
        visible: true,
        keepAlive: false,
        remark: "系统监控目录",
        createTime: new Date(),
        children: [
          {
            id: 21,
            parentId: 2,
            title: "在线用户",
            path: "/monitor/online",
            component: "monitor/online/index",
            icon: "online",
            permission: "monitor:online:list",
            type: 2,
            status: 1,
            sort: 1,
            visible: true,
            keepAlive: true,
            remark: "在线用户菜单",
            createTime: new Date()
          }
        ]
      }
    ];

    // 简单的过滤逻辑
    if (params.title) {
      menuData = filterMenuByTitle(menuData, params.title);
    }
    if (params.status !== "") {
      menuData = filterMenuByStatus(menuData, params.status);
    }

    return menuData;
  }

  // 递归过滤菜单标题
  function filterMenuByTitle(data: any[], title: string): any[] {
    return data.filter(item => {
      if (item.title.includes(title)) {
        return true;
      }
      if (item.children && item.children.length > 0) {
        item.children = filterMenuByTitle(item.children, title);
        return item.children.length > 0;
      }
      return false;
    });
  }

  // 递归过滤菜单状态
  function filterMenuByStatus(data: any[], status: number): any[] {
    return data.filter(item => {
      if (item.status === status) {
        if (item.children && item.children.length > 0) {
          item.children = filterMenuByStatus(item.children, status);
        }
        return true;
      }
      if (item.children && item.children.length > 0) {
        item.children = filterMenuByStatus(item.children, status);
        return item.children.length > 0;
      }
      return false;
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    onSearch,
    resetForm,
    openDialog,
    handleDelete
  };
}
